﻿using ERPWinFormWork.Sales.DTO.Output;
using ERPWinFormWork.Sales;
using ERPWinFormWork.Test.Test.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.Test.Dtos.Write;
using System.Drawing.Printing;
using ERPWinFormWork.Test.TestCode;

namespace ERPWinFormWork.Test
{
    public partial class AddOutInspection : Form
    {
        private ApiClient _apiClient;
        private Inspection inspection;
        private int? _selectedSaleId;
        private int? _selectedProductId;
        private Action _onSuccessCallback; // 添加成功后的回调函数

        public AddOutInspection(Action onSuccessCallback = null)
        {
            _onSuccessCallback = onSuccessCallback;
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            InitializeComponent();

            // 统一UI美化（不改变功能，仅优化观感）
            ApplyUiPolish();

            // 根据时间自动生成检验编号（时间戳）
            textinspectionNode.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            this.inspection = inspection;

            // 初始化日期控件
            InitializeDateControls();
            // 配置表格，避免末尾空白行并加入操作列
            ConfigureTestingItemsGrid();
            this.dgvtesting_ItemsId.CellContentClick += dgvtesting_ItemsId_CellContentClick;
            this.dgvtesting_ItemsId.DataBindingComplete += Dgvtesting_ItemsId_DataBindingComplete;

            // 添加数量变化事件监听器，用于自动计算
            AddCalculationEventListeners();

            // 初始化默认值
            InitializeDefaultValues();

            // 确保控件已正确初始化后再加载数据
            LoadDropdownData();

            // 验证控件是否正确初始化
            ValidateControls();
        }

        private void ApplyUiPolish()
        {
            try
            {
                // 全局字体与背景（与入货检验一致）
                this.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
                this.BackColor = Color.FromArgb(248, 250, 252);

                // 标签统一前景色
                var dark = Color.FromArgb(64, 64, 64);
                foreach (Control c in this.Controls)
                {
                    if (c is CCWin.SkinControl.SkinLabel lbl)
                    {
                        lbl.ForeColor = dark;
                    }
                }

                // 规范按钮尺寸与字体
                Action<Control> styleButton = ctrl =>
                {
                    if (ctrl == null) return;
                    // 为 WinForms Button 与 CCWin SkinButton 同步设置
                    if (ctrl is Button)
                    {
                        var btn = (Button)ctrl;
                        ApplyButtonStyle(btn, btn.Text);
                    }
                    else if (ctrl is CCWin.SkinControl.SkinButton)
                    {
                        var sbtn = (CCWin.SkinControl.SkinButton)ctrl;
                        ApplyButtonStyle(sbtn, sbtn.Text);
                    }
                };

                foreach (Control c in this.Controls)
                {
                    styleButton(c);
                }

                // 常见命名按钮的兜底处理（若位于容器内部）
                styleButton(this.Controls.Find("btnAddout", true).FirstOrDefault());
                styleButton(this.Controls.Find("btnClose", true).FirstOrDefault());
                styleButton(this.Controls.Find("btnaddinspe", true).FirstOrDefault());
                styleButton(this.Controls.Find("btnp", true).FirstOrDefault()); // 选择产品

                // 日期控件：统一高度（不设置水印，避免与设计器冲突）
                if (datetimeshipment_Date != null && datetimeshipment_Date.Size.Height < 32)
                {
                    datetimeshipment_Date.Size = new Size(datetimeshipment_Date.Width, 32);
                }
                if (datetimeinspection_Date != null && datetimeinspection_Date.Size.Height < 32)
                {
                    datetimeinspection_Date.Size = new Size(datetimeinspection_Date.Width, 32);
                }

                // 部门下拉框：统一高度
                if (this.Controls.Find("cboadddepartment_Id", true).FirstOrDefault() is ComboBox cboDept)
                {
                    if (cboDept.Height < 32)
                    {
                        cboDept.Size = new Size(cboDept.Width, 32);
                    }
                }

                // 表格美化
                if (dgvtesting_ItemsId != null)
                {
                    dgvtesting_ItemsId.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    dgvtesting_ItemsId.EnableHeadersVisualStyles = false;
                    dgvtesting_ItemsId.ColumnHeadersHeight = 40;
                    dgvtesting_ItemsId.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                    dgvtesting_ItemsId.RowTemplate.Height = 28;
                    dgvtesting_ItemsId.GridColor = Color.FromArgb(224, 224, 224);

                    dgvtesting_ItemsId.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(41, 128, 185);
                    dgvtesting_ItemsId.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
                    dgvtesting_ItemsId.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvtesting_ItemsId.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 10F, FontStyle.Bold);

                    dgvtesting_ItemsId.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                    dgvtesting_ItemsId.DefaultCellStyle.SelectionBackColor = Color.FromArgb(59, 188, 240);
                    dgvtesting_ItemsId.DefaultCellStyle.SelectionForeColor = Color.White;

                    // 双缓冲，减少闪烁
                    var pi = typeof(DataGridView).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    pi?.SetValue(dgvtesting_ItemsId, true, null);
                }
            }
            catch { }
        }

        private void ApplyButtonStyle(Control btn, string text)
        {
            // 默认：常规按钮
            var defaultSize = new Size(90, 36);
            var defaultFont = new Font("微软雅黑", 10.5F, FontStyle.Regular);

            // 根据按钮语义匹配尺寸/字体（与 AddInInspection 统一）
            if (text == "提交")
            {
                btn.Size = new Size(90, 40);
                btn.Font = new Font("微软雅黑", 11F, FontStyle.Bold);
            }
            else if (text == "关闭")
            {
                btn.Size = new Size(90, 40);
                btn.Font = new Font("微软雅黑", 11F, FontStyle.Regular);
            }
            else if (text == "新增检测项")
            {
                btn.Size = new Size(110, 38);
                btn.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular);
            }
            else if (text == "选择")
            {
                btn.Size = new Size(60, 30);
                btn.Font = new Font("微软雅黑", 9F, FontStyle.Regular);
            }
            else
            {
                btn.Size = defaultSize;
                btn.Font = defaultFont;
            }
        }

        /// <summary>
        /// 添加数量变化事件监听器，用于自动计算
        /// 注意：检测项目变化时会清空相关字段，计算只在输入合格数量后触发
        /// </summary>
        private void AddCalculationEventListeners()
        {
            Console.WriteLine("开始设置事件监听器...");

            // 监听检测数量和合格数量的变化
            if (textinspection_Count != null)
            {
                textinspection_Count.TextChanged += (s, e) =>
                {
                    Console.WriteLine("检测数量发生变化，触发计算");
                    // 立即执行计算，不延迟
                    CalculateQuantitiesAndRates();
                };
                Console.WriteLine("检测数量变化事件监听器设置成功");
            }
            else
            {
                Console.WriteLine("警告：检测数量控件不存在");
            }

            if (textqualified_Count != null)
            {
                textqualified_Count.TextChanged += (s, e) =>
                {
                    Console.WriteLine("合格数量发生变化，触发计算");
                    // 立即执行计算，不延迟
                    CalculateQuantitiesAndRates();
                };
                Console.WriteLine("合格数量变化事件监听器设置成功");
            }
            else
            {
                Console.WriteLine("警告：合格数量控件不存在");
            }

            // 监听表格中缺陷数量的变化
            if (dgvtesting_ItemsId != null)
            {
                dgvtesting_ItemsId.CellValueChanged += (s, e) =>
                {
                    // 只有当缺陷数量列发生变化时才重新计算
                    if (e.ColumnIndex >= 0 && dgvtesting_ItemsId.Columns[e.ColumnIndex] != null)
                    {
                        string columnName = dgvtesting_ItemsId.Columns[e.ColumnIndex].Name;
                        if (columnName == "colFatalCount" || columnName == "colSeriousCount" || columnName == "colMinorCount")
                        {
                            Console.WriteLine($"缺陷数量发生变化 - 列: {columnName}, 值: {e}");
                            // 立即重新计算，不延迟
                            CalculateQuantitiesAndRates();
                        }
                    }
                };
                Console.WriteLine("表格缺陷数量变化事件监听器设置成功");

                // 监听数据源变化，当检测项目增加或减少时清空相关字段
                dgvtesting_ItemsId.DataSourceChanged += (s, e) =>
                {
                    Console.WriteLine("检测项目数据源发生变化，清空相关字段");
                    // 检测项目变化时，立即清空相关字段，等待用户重新输入合格数量
                    ClearCalculationResults();
                    ClearAllDefectCounts();
                };
                Console.WriteLine("表格数据源变化事件监听器设置成功");
            }
            else
            {
                Console.WriteLine("警告：检测项目表格控件不存在");
            }

            // 设置缺陷率文本框为只读，因为它们是自动计算的
            SetDefectRateTextBoxesReadOnly();
            Console.WriteLine("事件监听器设置完成");
        }

        /// <summary>
        /// 设置缺陷率文本框为只读
        /// </summary>
        private void SetDefectRateTextBoxesReadOnly()
        {
            if (textfatal_Defect_Rate != null)
            {
                textfatal_Defect_Rate.ReadOnly = true;
            }
            if (textserious_Defect_Rate != null)
            {
                textserious_Defect_Rate.ReadOnly = true;
            }
            if (textminor_Defect_Rate != null)
            {
                textminor_Defect_Rate.ReadOnly = true;
            }
            if (textnoQualified_Count != null)
            {
                textnoQualified_Count.ReadOnly = true;
            }
            if (textdetection_Result != null)
            {
                textdetection_Result.ReadOnly = true;
            }
        }

        /// <summary>
        /// 初始化默认值
        /// </summary>
        private void InitializeDefaultValues()
        {
            // 设置默认的检测结果
            if (textdetection_Result != null)
            {
                textdetection_Result.Text = "合格";
            }

            // 设置默认的缺陷率为0
            if (textfatal_Defect_Rate != null)
            {
                textfatal_Defect_Rate.Text = "0.00";
            }
            if (textserious_Defect_Rate != null)
            {
                textserious_Defect_Rate.Text = "0.00";
            }
            if (textminor_Defect_Rate != null)
            {
                textminor_Defect_Rate.Text = "0.00";
            }

            // 设置默认的不合格数量为0
            if (textnoQualified_Count != null)
            {
                textnoQualified_Count.Text = "0";
            }
        }

        /// <summary>
        /// 自动计算不合格数量和缺陷率
        /// </summary>
        private void CalculateQuantitiesAndRates()
        {
            try
            {
                Console.WriteLine("=== 开始计算缺陷率 ===");

                // 检查是否有检测项目
                if (dgvtesting_ItemsId == null || dgvtesting_ItemsId.Rows.Count == 0)
                {
                    Console.WriteLine("没有检测项目，清空计算结果");
                    // 没有检测项目时，清空计算结果
                    ClearCalculationResults();
                    return;
                }

                Console.WriteLine($"检测项目数量: {dgvtesting_ItemsId.Rows.Count}");

                // 检查控件是否存在
                if (textinspection_Count == null || textqualified_Count == null)
                {
                    Console.WriteLine("控件不存在，退出计算");
                    return;
                }

                // 获取文本值并立即验证
                string inspectionCountText = textinspection_Count.Text?.Trim();
                string qualifiedCountText = textqualified_Count.Text?.Trim();

                Console.WriteLine($"检测数量文本: '{inspectionCountText}', 合格数量文本: '{qualifiedCountText}'");

                // 检查是否为空
                if (string.IsNullOrEmpty(inspectionCountText) || string.IsNullOrEmpty(qualifiedCountText))
                {
                    Console.WriteLine("检测数量或合格数量为空，清空计算结果");
                    // 清空计算结果
                    ClearCalculationResults();
                    return;
                }

                // 解析检测数量和合格数量
                if (!int.TryParse(inspectionCountText, out int inspectionCount) || inspectionCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                if (!int.TryParse(qualifiedCountText, out int qualifiedCount) || qualifiedCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 验证合格数量不能超过检测数量
                if (qualifiedCount > inspectionCount)
                {
                    // 如果合格数量超过检测数量，清空计算结果
                    ClearCalculationResults();
                    return;
                }

                // 验证检测数量必须大于0
                if (inspectionCount <= 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 计算不合格数量
                int noQualifiedCount = Math.Max(0, inspectionCount - qualifiedCount);

                // 更新不合格数量文本框
                if (textnoQualified_Count != null)
                {
                    textnoQualified_Count.Text = noQualifiedCount.ToString();
                }

                // 计算各类缺陷数量总和
                int totalFatal = 0, totalSerious = 0, totalMinor = 0;

                if (dgvtesting_ItemsId != null && dgvtesting_ItemsId.Rows.Count > 0)
                {
                    Console.WriteLine($"开始遍历 {dgvtesting_ItemsId.Rows.Count} 行数据");

                    // 遍历所有行，累加各类缺陷数量
                    foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                    {
                        Console.WriteLine($"处理第 {row.Index} 行");

                        // 获取致命缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                        {
                            string fatalValue = row.Cells["colFatalCount"].Value.ToString();
                            Console.WriteLine($"行 {row.Index} 致命缺陷值: '{fatalValue}'");
                            if (int.TryParse(fatalValue, out int fatal) && fatal >= 0)
                            {
                                totalFatal += fatal;
                                Console.WriteLine($"行 {row.Index} 致命缺陷累加: {fatal}, 总计: {totalFatal}");
                            }
                        }

                        // 获取严重缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                        {
                            string seriousValue = row.Cells["colSeriousCount"].Value.ToString();
                            Console.WriteLine($"行 {row.Index} 严重缺陷值: '{seriousValue}'");
                            if (int.TryParse(seriousValue, out int serious) && serious >= 0)
                            {
                                totalSerious += serious;
                                Console.WriteLine($"行 {row.Index} 严重缺陷累加: {serious}, 总计: {totalSerious}");
                            }
                        }

                        // 获取轻微缺陷数量
                        if (dgvtesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                        {
                            string minorValue = row.Cells["colMinorCount"].Value.ToString();
                            Console.WriteLine($"行 {row.Index} 轻微缺陷值: '{minorValue}'");
                            if (int.TryParse(minorValue, out int minor) && minor >= 0)
                            {
                                totalMinor += minor;
                                Console.WriteLine($"行 {row.Index} 轻微缺陷累加: {minor}, 总计: {totalMinor}");
                            }
                        }
                    }
                }

                Console.WriteLine($"缺陷数量统计 - 致命: {totalFatal}, 严重: {totalSerious}, 轻微: {totalMinor}, 检测数量: {inspectionCount}");

                // 计算缺陷率（百分比）
                double fatalRate = inspectionCount > 0 ? (double)totalFatal / inspectionCount * 100 : 0;
                double seriousRate = inspectionCount > 0 ? (double)totalSerious / inspectionCount * 100 : 0;
                double minorRate = inspectionCount > 0 ? (double)totalMinor / inspectionCount * 100 : 0;

                Console.WriteLine($"缺陷率计算 - 致命: {fatalRate:F2}%, 严重: {seriousRate:F2}%, 轻微: {minorRate:F2}%");
                Console.WriteLine($"计算详情 - 致命: {totalFatal}/{inspectionCount}*100 = {fatalRate:F2}%");
                Console.WriteLine($"计算详情 - 严重: {totalSerious}/{inspectionCount}*100 = {seriousRate:F2}%");
                Console.WriteLine($"计算详情 - 轻微: {totalMinor}/{inspectionCount}*100 = {minorRate:F2}%");

                // 更新缺陷率文本框
                if (textfatal_Defect_Rate != null)
                {
                    textfatal_Defect_Rate.Text = fatalRate.ToString("F2");
                    Console.WriteLine($"更新致命缺陷率文本框: {fatalRate:F2}");
                }
                if (textserious_Defect_Rate != null)
                {
                    textserious_Defect_Rate.Text = seriousRate.ToString("F2");
                    Console.WriteLine($"更新严重缺陷率文本框: {seriousRate:F2}");
                }
                if (textminor_Defect_Rate != null)
                {
                    textminor_Defect_Rate.Text = minorRate.ToString("F2");
                    Console.WriteLine($"更新轻微缺陷率文本框: {minorRate:F2}");
                }

                // 根据缺陷率判断检测结果
                string detectionResult = DetermineDetectionResult(fatalRate, seriousRate, minorRate);
                if (textdetection_Result != null)
                {
                    textdetection_Result.Text = detectionResult;
                    Console.WriteLine($"更新检测结果: {detectionResult}");
                }

                Console.WriteLine("=== 缺陷率计算完成 ===");
            }
            catch (Exception ex)
            {
                // 静默处理异常，避免影响用户输入
                Console.WriteLine($"计算过程中出现异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 清空计算结果
        /// </summary>
        private void ClearCalculationResults()
        {
            // 清空不合格数量
            if (textnoQualified_Count != null)
            {
                textnoQualified_Count.Text = "0";
            }

            // 清空缺陷率
            if (textfatal_Defect_Rate != null)
            {
                textfatal_Defect_Rate.Text = "0.00";
            }
            if (textserious_Defect_Rate != null)
            {
                textserious_Defect_Rate.Text = "0.00";
            }
            if (textminor_Defect_Rate != null)
            {
                textminor_Defect_Rate.Text = "0.00";
            }

            // 清空检测结果
            if (textdetection_Result != null)
            {
                textdetection_Result.Text = "合格";
            }

            // 清空检测数量和合格数量，强制用户重新输入
            if (textinspection_Count != null)
            {
                textinspection_Count.Text = "";
            }
            if (textqualified_Count != null)
            {
                textqualified_Count.Text = "";
            }

            // 显示提示信息
            Console.WriteLine("检测项目已变化，相关字段已清空，请重新输入检测数量和合格数量");
        }

        /// <summary>
        /// 清除所有缺陷数量
        /// </summary>
        private void ClearAllDefectCounts()
        {
            if (dgvtesting_ItemsId != null && dgvtesting_ItemsId.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
                {
                    if (dgvtesting_ItemsId.Columns.Contains("colFatalCount"))
                    {
                        row.Cells["colFatalCount"].Value = 0;
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount"))
                    {
                        row.Cells["colSeriousCount"].Value = 0;
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colMinorCount"))
                    {
                        row.Cells["colMinorCount"].Value = 0;
                    }

                }
            }
        }

        /// <summary>
        /// 根据缺陷率判断检测结果
        /// </summary>
        /// <param name="fatalRate">致命缺陷率</param>
        /// <param name="seriousRate">严重缺陷率</param>
        /// <param name="minorRate">轻微缺陷率</param>
        /// <returns>检测结果：合格 或 不合格</returns>
        private string DetermineDetectionResult(double fatalRate, double seriousRate, double minorRate)
        {
            // 致命缺陷率不能超过5%，严重缺陷率不能超过7%，轻微缺陷率不能超过10%
            if (fatalRate > 5.0 || seriousRate > 7.0 || minorRate > 10.0)
            {
                return "不合格";
            }
            else
            {
                return "合格";
            }
        }

        /// <summary>
        /// 验证数量输入
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateQuantityInputs()
        {
            // 验证检测数量
            if (!int.TryParse(textinspection_Count.Text, out int inspectionCount) || inspectionCount <= 0)
            {
                MessageBox.Show("请输入有效的检测数量（必须大于0）", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证合格数量
            if (!int.TryParse(textqualified_Count.Text, out int qualifiedCount) || qualifiedCount < 0)
            {
                MessageBox.Show("请输入有效的合格数量（不能为负数）", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证合格数量不能超过检测数量
            if (qualifiedCount > inspectionCount)
            {
                MessageBox.Show("合格数量不能超过检测数量", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }





        // 加载部门下拉框数据
        private async Task LoadDropdownData()
        {
            // 示例：加载部门下拉框
            var deptResponse = await _apiClient.GetAsync<TestApiResult<List<DepartmentDtos>>>(
                endpoint: "api/Read/GetDepartment");

            if (deptResponse != null && deptResponse.code == 200)
            {
                // 清空并添加默认项
                cboadddepartment_Id.Items.Clear();
                cboadddepartment_Id.DisplayMember = "departmentName"; // 显示部门名称
                cboadddepartment_Id.ValueMember = "id";                 // 实际值存部门 ID
                cboadddepartment_Id.DataSource = deptResponse.data;
                cboadddepartment_Id.SelectedItem = null;


            }

        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAddout_Click(object sender, EventArgs e)
        {
            // 校验至少选择了一个检验项目
            if (dgvtesting_ItemsId.Rows.Count == 0)
            {
                MessageBox.Show("请先选择检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 验证数量输入
            if (!ValidateQuantityInputs())
            {
                return;
            }

            // 获取用户选择的日期
            DateTime shipmentDate;
            DateTime inspectionDate;

            // 解析发货日期
            if (!DateTime.TryParse(datetimeshipment_Date.text, out shipmentDate))
            {
                MessageBox.Show("请输入有效的发货日期", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 解析检验日期
            if (!DateTime.TryParse(datetimeinspection_Date.text, out inspectionDate))
            {
                MessageBox.Show("请输入有效的检验日期", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 解析下拉选项
            int departmentId = 0;
            if (cboadddepartment_Id.SelectedValue != null)
            {
                int.TryParse(cboadddepartment_Id.SelectedValue.ToString(), out departmentId);
            }


            // 解析数量
            int inspectionCount = int.TryParse(textinspection_Count.Text, out var tmpCount) ? tmpCount : 0;
            int qualifiedCount = int.TryParse(textqualified_Count.Text, out var tmpQ) ? tmpQ : 0;
            int noQualifiedCount = int.TryParse(textnoQualified_Count.Text, out var tmpNQ) ? tmpNQ : 0;

            // 解析缺陷率（使用计算出的值）
            double fatalRate = double.TryParse(textfatal_Defect_Rate.Text, out var tmpFR) ? tmpFR : 0;
            double seriousRate = double.TryParse(textserious_Defect_Rate.Text, out var tmpSR) ? tmpSR : 0;
            double minorRate = double.TryParse(textminor_Defect_Rate.Text, out var tmpMR) ? tmpMR : 0;

            var list = new List<CreateGoods_InspectionDtos>();
            foreach (DataGridViewRow row in dgvtesting_ItemsId.Rows)
            {
                if (row.DataBoundItem is Testing_ItemsDtos item)
                {
                    int fatal = 0, serious = 0, minor = 0;
                    if (dgvtesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                    {
                        int.TryParse(row.Cells["colFatalCount"].Value.ToString(), out fatal);
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                    {
                        int.TryParse(row.Cells["colSeriousCount"].Value.ToString(), out serious);
                    }
                    if (dgvtesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                    {
                        int.TryParse(row.Cells["colMinorCount"].Value.ToString(), out minor);
                    }

                    list.Add(new CreateGoods_InspectionDtos
                    {
                        Inspection_Type = 2, // 出货检验
                        InspectionNode = textinspectionNode.Text?.Trim(),
                        InspectionName = textinspectionName.Text?.Trim(),
                        Shipment_Date = shipmentDate,
                        Inspection_Date = inspectionDate,
                        Department_Id = departmentId,
                        User_Id = 10038,
                        Sale_Id = _selectedSaleId,
                        ProductId = _selectedProductId,
                        Purchase_Id = null,
                        MaterialId = null,
                        Batch = textaddbatch.Text?.Trim(),
                        Testing_ItemsId = item.Id,
                        Fatal_DefectCount = fatal,
                        Serious_DefectCount = serious,
                        Minor_DefectCount = minor,
                        Inspection_Count = inspectionCount,
                        Qualified_Count = qualifiedCount,
                        NoQualified_Count = noQualifiedCount,
                        Fatal_Defect_Rate = (int)Math.Round(fatalRate),
                        Serious_Defect_Rate = (int)Math.Round(seriousRate),
                        Minor_Defect_Rate = (int)Math.Round(minorRate),
                        Detection_Result = textdetection_Result.Text?.Trim(),
                        Notes = textnotes.Text?.Trim()
                    });
                }
            }

            if (list.Count == 0)
            {
                MessageBox.Show("请选择至少一条检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 根据后端接口要求，使用 items 字段名
            var payload = new { items = list };

            var resp = await _apiClient.PostAsync<object, TestApiResult<string>>(
                endpoint: "api/Write/CreateGoods_Inspection",
                data: payload
            );

            if (resp != null && resp.code == 200)
            {
                MessageBox.Show("新增检验单成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 调用回调函数刷新父窗体数据
                _onSuccessCallback?.Invoke();

                this.Close();
            }
            else
            {
                MessageBox.Show($"新增失败：{resp?.msg ?? "接口调用失败"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增检测项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnaddinspe_Click(object sender, EventArgs e)
        {
            var dialog = new GetInspection(onSelected: items =>
            {
                if (items == null || items.Count == 0) return;
                // 确保网格配置完成（不会重复添加列）
                ConfigureTestingItemsGrid();
                if (dgvtesting_ItemsId.DataSource is BindingList<Testing_ItemsDtos> binding)
                {
                    foreach (var it in items)
                    {
                        if (!binding.Any(x => x.Id == it.Id))
                        {
                            binding.Add(it);
                        }
                    }
                }
                else
                {
                    dgvtesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(items);
                }

                // 添加检测项目后，清空相关字段，等待用户重新输入合格数量
                ClearCalculationResults();
                ClearAllDefectCounts();
            });

            dialog.Show();
        }

        // 配置检测项目网格：禁用新增行、添加操作列（缺陷填报/删除）
        private void ConfigureTestingItemsGrid()
        {
            var grid = dgvtesting_ItemsId;
            grid.AllowUserToAddRows = false; // 不显示底部空白“新行”

            // 已添加则跳过
            if (!grid.Columns.Contains("colFatalCount"))
            {
                var colFatal = new DataGridViewTextBoxColumn
                {
                    Name = "colFatalCount",
                    HeaderText = "致命缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colFatal);
            }

            if (!grid.Columns.Contains("colSeriousCount"))
            {
                var colSerious = new DataGridViewTextBoxColumn
                {
                    Name = "colSeriousCount",
                    HeaderText = "严重缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colSerious);
            }

            if (!grid.Columns.Contains("colMinorCount"))
            {
                var colMinor = new DataGridViewTextBoxColumn
                {
                    Name = "colMinorCount",
                    HeaderText = "轻微缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colMinor);
            }

            if (!grid.Columns.Contains("colDefect"))
            {
                var defectCol = new DataGridViewButtonColumn
                {
                    Name = "colDefect",
                    HeaderText = "操作",
                    Text = "缺陷填报",
                    UseColumnTextForButtonValue = true,
                    Width = 90
                };
                grid.Columns.Add(defectCol);
            }

            if (!grid.Columns.Contains("colDelete"))
            {
                var deleteCol = new DataGridViewButtonColumn
                {
                    Name = "colDelete",
                    HeaderText = string.Empty,
                    Text = "删除",
                    UseColumnTextForButtonValue = true,
                    Width = 70
                };
                grid.Columns.Add(deleteCol);
            }
        }

        // 操作列点击事件
        private void dgvtesting_ItemsId_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            var grid = dgvtesting_ItemsId;
            var name = grid.Columns[e.ColumnIndex].Name;

            if (name == "colDelete")
            {
                grid.Rows.RemoveAt(e.RowIndex);
                // 删除检测项目后，清空相关字段，等待用户重新输入合格数量
                ClearCalculationResults();
                ClearAllDefectCounts();
                return;
            }

            if (name == "colDefect")
            {
                // 打开缺陷选择窗体，回填数量到当前行
                var currentRowIndex = e.RowIndex;
                var form = new DefectSelectForm((fatal, serious, minor) =>
                {
                    var row = dgvtesting_ItemsId.Rows[currentRowIndex];
                    row.Cells["colFatalCount"].Value = fatal;
                    row.Cells["colSeriousCount"].Value = serious;
                    row.Cells["colMinorCount"].Value = minor;

                    Console.WriteLine($"缺陷选择回填 - 行: {currentRowIndex}, 致命: {fatal}, 严重: {serious}, 轻微: {minor}");

                    // 触发重新计算
                    CalculateQuantitiesAndRates();
                });
                form.Show(this);
            }
        }

        // 数据绑定完成后：将操作列放到最后，并把部分列头改为中文
        private void Dgvtesting_ItemsId_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var grid = dgvtesting_ItemsId;
            grid.AllowUserToAddRows = false;

            if (grid.Columns.Contains("Items_Name")) grid.Columns["Items_Name"].HeaderText = "检测项目";
            if (grid.Columns.Contains("DetectionType_Name")) grid.Columns["DetectionType_Name"].HeaderText = "检验类型";
            if (grid.Columns.Contains("Tools_Name")) grid.Columns["Tools_Name"].HeaderText = "检验工具";

            // 把操作列放到最后
            int count = grid.Columns.Count;
            if (count <= 0) return;
            var orderTail = new List<string> { "colDelete", "colDefect", "colMinorCount", "colSeriousCount", "colFatalCount" };
            int current = count - 1;
            foreach (var name in orderTail)
            {
                if (grid.Columns.Contains(name))
                {
                    grid.Columns[name].DisplayIndex = current;
                    current--;
                }
            }

            // 列重新排序完成后，清空相关字段，等待用户重新输入合格数量
            ClearCalculationResults();
            ClearAllDefectCounts();
        }

        /// <summary>
        /// 弹出产品框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnp_Click(object sender, EventArgs e)
        {
            var dialog = new ProductSelectForm(onSelected: prod =>
            {
                if (prod == null) return;
                textproductname.Text = prod.Product_Name ?? string.Empty;
                textproductcode.Text = prod.Product_Number ?? string.Empty;
                textproductunit.Text = prod.Unit ?? string.Empty;
                textproductxh.Text = prod.Specification ?? string.Empty;
                _selectedSaleId = prod.Id;
                _selectedProductId = prod.ProductId;
                // 批次号由用户输入；如果有来源字段可在此赋值
            });
            dialog.Show(this);
        }

        /// <summary>
        /// 初始化日期控件
        /// </summary>
        private void InitializeDateControls()
        {
            // 设置发货日期为当前日期，但允许用户修改
            if (datetimeshipment_Date != null)
            {
                datetimeshipment_Date.text = DateTime.Now.ToString("yyyy-MM-dd");
            }

            // 设置检验日期为当前日期，但允许用户修改
            if (datetimeinspection_Date != null)
            {
                datetimeinspection_Date.text = DateTime.Now.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 验证控件是否正确初始化
        /// </summary>
        private void ValidateControls()
        {
            // 检查关键控件是否存在
            if (textinspection_Count == null)
            {
                MessageBox.Show("检测数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textqualified_Count == null)
            {
                MessageBox.Show("合格数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textnoQualified_Count == null)
            {
                MessageBox.Show("不合格数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textfatal_Defect_Rate == null)
            {
                MessageBox.Show("致命缺陷率控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textserious_Defect_Rate == null)
            {
                MessageBox.Show("严重缺陷率控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textminor_Defect_Rate == null)
            {
                MessageBox.Show("轻微缺陷率控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textdetection_Result == null)
            {
                MessageBox.Show("检测结果控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 测试计算方法（可选，用于调试）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TestCalculation_Click(object sender, EventArgs e)
        {
            // 设置测试数据
            if (textinspection_Count != null)
            {
                textinspection_Count.Text = "100";
            }
            if (textqualified_Count != null)
            {
                textqualified_Count.Text = "95";
            }

            // 手动触发计算
            CalculateQuantitiesAndRates();

            MessageBox.Show("测试计算完成，请检查结果", "测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

